<template>
  <BasicsForm
    :btn-group-options="btnGroupOptions"
    @register="basicsFormRegister"
    @submit="onSubmit"
    @onSchemaChange="onChange"
  ></BasicsForm>
</template>

<script setup lang="ts">
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm } from '@/components/Form';
  import { stageForm, memberTypeGetList } from '@/api/membership';
  import { propTypes } from '@/utils/propTypes';
  import { handleField } from './components/conf';
  import { type PropType } from 'vue';
  import { IsInternalInterfaceEnum, IsRequired } from '@/enums/formEnum';
  import dictionary from '@/utils/dictionary';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import { type customFormUserAnswerList } from '@/api/membership/types';
  import { getTianyanchaDetail } from '@/components/Form/utils/tianyancha';
  import { type OnchangeArgument } from '@/components/Form/types';
  import { type CardBottomBtnsOptions } from '@/components/TButtonGroup/types';
  import type { ApplyTypeEnum } from '@/enums/membershipEnum';

  const props = defineProps({
    stageId: propTypes.number,
    applicantType: Number as PropType<ApplyTypeEnum>,
    // 当前阶段回显数据
    currentData: {
      type: Array as PropType<customFormUserAnswerList[]>,
    },
    btnGroupOptions: Object as PropType<CardBottomBtnsOptions>,
  });
  const emit = defineEmits(['onLoad', 'onSubmit', 'onChange']);

  const [register, { appendSchemaByField, updateSchema, setFieldsValue, getSchemas }] = useForm({
    labelPosition: 'left',
    labelAlign: 'left',
    labelWidth: 140,
    schemas: [],
  });

  async function basicsFormRegister(event: any) {
    register(event);
    getFormComp();
  }

  /** 获取表单模板 */
  async function getFormComp() {
    const { stageId, currentData } = props;
    const { formGroupMap, formItemVoMap } = await stageForm(stageId);
    const typeDataName: { type: string; field: string }[] = [];
    const dictDataName: { type: string; field: string }[] = [];

    for (let i = 0; i < formGroupMap.length; i++) {
      const item = formGroupMap[i];
      appendSchemaByField({
        field: 'Divider' + item.id,
        component: 'Divider',
        label: item.name,
      });
      if (formItemVoMap && formItemVoMap.hasOwnProperty(item.id)) {
        let formItems = formItemVoMap[item.id];
        formItems.map((v) => {
          let field = handleField(stageId, { groupId: v.formGroupId, id: v.id }) as string;
          if (v.isInternalInterface === IsInternalInterfaceEnum.CLASSIFICATION)
            typeDataName.push({ field, type: v.type });
          if (v.isInternalInterface === IsInternalInterfaceEnum.DICTIONARY)
            dictDataName.push({ field, type: v.type });
          let defaultValue;

          // 数据回显
          currentData &&
            currentData.map((cv) => {
              let cField = handleField(cv.formStageId, {
                groupId: cv.formGroupId,
                id: cv.formItemId,
              }) as string;
              if (field === cField) {
                defaultValue = cv.content;
              }
            });

          appendSchemaByField({
            field,
            component: v.itemType,
            label: v.showName,
            dataType: v.dataType,
            isInternalInterface: v.isInternalInterface,
            dynamicDisabled: v.disabled,
            required: v.isRequired === IsRequired.REQUIRED,
            defaultValue: defaultValue,
            componentProps: {
              placeholder: v.value,
              limit: v.length,
              itemDefault: v.itemDefault,
              enableValue: v.enableValue,
              showGetPhone: true,
              localdata: localDataMapping(v.customFormItemAnswerList, {
                label: 'words',
                value: 'id',
              }),
            },
          });
        });
      }
    }

    await getFieldLocaldata(typeDataName, dictDataName);
    emit('onLoad');
  }

  async function getFieldLocaldata(
    typeDataName: { type: string; field: string }[] = [],
    dictDataName: { type: string; field: string }[] = [],
  ) {
    const updateSchemasValue = [];
    if (typeDataName.length) {
      const res = await memberTypeGetList(
        typeDataName.map((v) => v.type),
        'memberApply',
        props.applicantType,
      );
      for (let index = 0; index < typeDataName.length; index++) {
        const item = typeDataName[index];
        updateSchemasValue.push({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(res[item.type], { label: 'name', value: 'id' }),
          },
        });
      }
    }
    if (dictDataName.length) {
      const dictList = await dictionary.getMulti(dictDataName.map((v) => v.type));
      for (let index = 0; index < dictDataName.length; index++) {
        const item = dictDataName[index];
        updateSchemasValue.push({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(dictList[item.type], {
              label: 'dictLabel',
              value: 'dictValue',
            }),
          },
        });
      }
    }
    updateSchema(updateSchemasValue);
  }

  function onSubmit(e: any) {
    emit('onSubmit', e);
  }

  function onChange(e: OnchangeArgument) {
    if (e.component === 'InputSearch' && e.val) {
      getTianyanchaDetail(e).then((values) => {
        values && setFieldsValue(values);
      });
      emit('onChange', e);
    }
  }
</script>

<style scoped></style>
